package script
import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego"
	"controllers"
	"library/common"
)
type ScriptListController struct {
	controllers.BaseRouter
}
//返回执行结果
func (c *ScriptListController) TaskDetail () {
	taskId,_ := c.GetInt(":taskId")
	o := orm.NewOrm()
	var record []orm.Params
	var task   []orm.Params
	result := map[string]interface{}{}
	num,err := o.Raw("SELECT * FROM gj_script_record WHERE task_id = ?",taskId).Values(&record)
	if err != nil || num == 0{
		beego.Info(err.Error())
		c.SetJson(1, record, "获取脚本记录失败")
		return
	}
	num,err = o.Raw("SELECT * FROM gj_script_task WHERE id = ?",taskId).Values(&task)
	if err != nil || num == 0{
		beego.Info(err.Error())
		c.SetJson(1, record, "获取脚本任务失败")
		return
	}
	result["status"] = common.GetString(record[0]["status"])
	result["duration"] = common.GetString(record[0]["duration"])
	result["memo"] = common.GetString(record[0]["memo"])
	result["is_final"] = common.GetString(record[0]["is_final"])
	result["script_name"] = common.GetString(task[0]["script_name"])
	result["release_user"] = common.GetString(task[0]["release_user"])
	result["hosts"] = common.GetString(task[0]["hosts"])
	result["script_content"] = common.GetString(task[0]["script_content"])
	result["type"] = common.GetString(task[0]["type"])
	result["timeout"] = common.GetString(task[0]["timeout"])
	result["script_parms"] = common.GetString(task[0]["script_parms"])
	result["operator"] = common.GetString(task[0]["operator"])
	result["create_time"] = common.GetString(task[0]["create_time"])
	c.SetJson(200, result, "")
	return
}
func (c *ScriptListController) ScriptTaskList () {
	page, _ := c.GetInt("page", 0)
	start := 0
	length, _ := c.GetInt("length", 15)
	if page > 0 {
		start = (page - 1) * length
	}
	selectInfo := c.GetString("select_info")
	where := ""
	if selectInfo != "" {
		where = "  and( gj_script_task.script_name LIKE '%" + selectInfo + "%' or gj_script_task.release_user LIKE '%" + selectInfo + "%'  or gj_script_task.operator LIKE '%" + selectInfo + "%'  )"
	}
	var task []orm.Params
	o := orm.NewOrm()
	o.Raw("SELECT gj_script_task.* ,gj_script_record.is_final FROM `gj_script_task` LEFT JOIN `gj_script_record` ON gj_script_task.id = gj_script_record.task_id WHERE 1=1 "+where+" order by gj_script_task.id DESC  LIMIT ? ,?", start, length).Values(&task)
	var count []orm.Params
	total := 0
	o.Raw("SELECT count(gj_script_record.is_final) as total  FROM `gj_script_task` LEFT JOIN `gj_script_record` ON gj_script_task.id = gj_script_record.task_id WHERE 1=1 "+where).Values(&count)
	if len(count)>0{
	    total = common.GetInt(count[0]["total"])
	}
	c.SetJson(200,  map[string]interface{}{"total": total, "currentPage": page, "table_data": task}, "")
	return
}